package org.dromara.wmscloud.service.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.wmscloud.bean.typeEnum.InOrderCheckStatusEnum;
import org.dromara.wmscloud.bean.typeEnum.OrderStatusEnum;
import org.dromara.wmscloud.domain.StockInDetail;
import org.dromara.wmscloud.domain.StockMatLabel;
import org.dromara.wmscloud.domain.bo.StockInDetailBo;
import org.dromara.wmscloud.domain.bo.StockMatLabelBo;
import org.dromara.wmscloud.domain.vo.StockInDetailVo;
import org.dromara.wmscloud.mapper.StockInDetailMapper;
import org.dromara.wmscloud.mapper.StockMatLabelMapper;
import org.dromara.wmscloud.service.IStockInDetailService;
import org.dromara.wmscloud.service.IStockMatLabelService;
import org.dromara.wmscloud.utils.OrderNoUtil;
import org.springframework.stereotype.Service;
import org.dromara.wmscloud.domain.bo.StockInOrderBo;
import org.dromara.wmscloud.domain.vo.StockInOrderVo;
import org.dromara.wmscloud.domain.StockInOrder;
import org.dromara.wmscloud.mapper.StockInOrderMapper;
import org.dromara.wmscloud.service.IStockInOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 入库单Service业务层处理
 *
 * @author hou
 * @date 2025-04-17
 */
@RequiredArgsConstructor
@Service
public class StockInOrderServiceImpl implements IStockInOrderService {

    private final StockInOrderMapper baseMapper;
    private final StockMatLabelMapper stockMatLabelMapper;
    private final StockInDetailMapper stockInDetailMapper;
    private final IStockInDetailService stockInDetailService;
    private final IStockMatLabelService stockMatLabelService;


    /**
     * 查询入库单
     *
     * @param orderId 主键
     * @return 入库单
     */
    @Override
    public StockInOrderVo queryById(Long orderId) {
        StockInOrderVo stockInOrderVo = baseMapper.selectVoById(orderId);
        if (stockInOrderVo != null && StringUtils.isNotBlank(stockInOrderVo.getOrderNo())) {
            StockInDetailBo stockInDetailBo = new StockInDetailBo();
            stockInDetailBo.setOrderNo(stockInOrderVo.getOrderNo());
            List<StockInDetailVo> detailList = stockInDetailService.queryList(stockInDetailBo);
            stockInOrderVo.setDetailList(detailList);
        }
        return stockInOrderVo;
    }

    /**
     * 分页查询入库单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 入库单分页列表
     */
    @Override
    public TableDataInfo<StockInOrderVo> queryPageList(StockInOrderBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<StockInOrder> lqw = buildQueryWrapper(bo);
        Page<StockInOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的入库单列表
     *
     * @param bo 查询条件
     * @return 入库单列表
     */
    @Override
    public List<StockInOrderVo> queryList(StockInOrderBo bo) {
        LambdaQueryWrapper<StockInOrder> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<StockInOrder> buildQueryWrapper(StockInOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<StockInOrder> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(StockInOrder::getOrderId);
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), StockInOrder::getOrderNo, bo.getOrderNo());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderType()), StockInOrder::getOrderType, bo.getOrderType());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderStatus()), StockInOrder::getOrderStatus, bo.getOrderStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckStatus()), StockInOrder::getCheckStatus, bo.getCheckStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCheckBy()), StockInOrder::getCheckBy, bo.getCheckBy());
        lqw.eq(bo.getCreateTime() != null, StockInOrder::getCreateTime, bo.getCreateTime());
        return lqw;
    }

    /**
     * 新增入库单
     *
     * @param bo 入库单
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(StockInOrderBo bo) {
        StockInOrder add = MapstructUtils.convert(bo, StockInOrder.class);
        validEntityBeforeSave(add);

        //入库单信息
        String orderType = add.getOrderType();
        String orderNo = OrderNoUtil.getInOrderNo(orderType);
        add.setOrderNo(orderNo);
        add.setOrderStatus(OrderStatusEnum.CREATED.getValue());
        add.setCheckStatus(InOrderCheckStatusEnum.UN_CHECKOUT.getValue());

        //入库单详情
        List<StockInDetail> detailList = add.getDetailList();

        if(CollectionUtils.isNotEmpty(detailList)){
            int i = 1;
            StockMatLabel label = null;
            for(StockInDetail detail : detailList){
                detail.setOrderNo(orderNo);
                detail.setLineNo(i);
                detail.setStockInQuantity(detail.getQuantity());

                //修改物料标签-订单号
                label = new StockMatLabel();
                label.setLabelId(detail.getLabelId());
                label.setOrderNo(orderNo);
                label.setOrderType(orderType);
                stockMatLabelMapper.updateById(label);
                i++;
            }
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (!flag) {
            throw new ServiceException("入库单保存失败");
        }
        Boolean detailInsertSuccess = stockInDetailMapper.insertBatch(detailList);
        if (!Boolean.TRUE.equals(detailInsertSuccess)) {
            throw new ServiceException("物料明细保存失败");
        }
        return true;
    }

    /**
     * 修改入库单
     *
     * @param bo 入库单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(StockInOrderBo bo) {
        StockInOrder update = MapstructUtils.convert(bo, StockInOrder.class);
//        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(StockInOrder entity){
        //做一些数据校验,如唯一约束
        if (entity.getDetailList() == null || entity.getDetailList().isEmpty()) {
            throw new ServiceException("请选择物料标签");
        }
    }

    /**
     * 校验并批量删除入库单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 校验是否已打印、是否已检验
        }
        // 查询主表中的 orderNo
        List<String> orderNos = baseMapper.selectBatchIds(ids).stream()
            .map(StockInOrder::getOrderNo)
            .collect(Collectors.toList());

        List<StockInDetailVo> detailList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(orderNos)) {
            // 根据 orderNo 查询 detailIds 和 labelIds
            for (String orderNo : orderNos) {
                StockInDetailBo stockInDetailBo = new StockInDetailBo();
                stockInDetailBo.setOrderNo(orderNo);
                detailList = stockInDetailService.queryList(stockInDetailBo);
            }
            //根据detailIds删除子表中的数据
            List<Long> detailIds = detailList.stream()
                .map(StockInDetailVo::getDetailId)
                .collect(Collectors.toList());

            stockInDetailService.deleteWithValidByIds(detailIds, true);
            //根据labelIds更新物料标签表中的数据
            List<Long> labelIds = detailList.stream()
                .map(StockInDetailVo::getLabelId)
                .toList();
            for (Long labelId : labelIds) {
                StockMatLabelBo label = new StockMatLabelBo();
                label.setLabelId(labelId);
                label.setOrderNo("");
                label.setOrderType("");
                stockMatLabelService.updateByBo(label);
            }
        }

        return baseMapper.deleteByIds(ids) > 0;
    }
}
